package com.zhuoli.service.springboot.mybatis.rowbounds.repository.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhuoli.service.springboot.mybatis.rowbounds.repository.mapper.UserMapper;
import com.zhuoli.service.springboot.mybatis.rowbounds.repository.model.User;
import com.zhuoli.service.springboot.mybatis.rowbounds.repository.model.UserExample;
import com.zhuoli.service.springboot.mybatis.rowbounds.repository.service.UserRepository;
import lombok.AllArgsConstructor;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: zhuoli
 * @Date: 2018/8/2 10:51
 * @Description:
 */
@Repository
@AllArgsConstructor
public class UserRepositoryImpl implements UserRepository {

    private UserMapper userMapper;

    @Override
    public List<User> getAllUsers() {
        UserExample example = new UserExample();
        return userMapper.selectByExample(example);
    }

    @Override
    public List<User> getUserByRowBounds(String userName, String description, RowBounds rowBounds) {
        UserExample example = new UserExample();
        /*动态sql，userName和description不为null，则作为查询条件查询*/
        UserExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isNullOrEmpty(userName)) {
            criteria.andUserNameLike("%" + userName + "%");
        }
        if (!StringUtils.isNullOrEmpty(description)) {
            criteria.andDescriptionEqualTo(description);
        }
        return userMapper.selectByExampleWithRowbounds(example, rowBounds);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delUserById(Long id) {
        UserExample example = new UserExample();
        example.createCriteria().andIdEqualTo(id);
        return userMapper.deleteByExample(example);
        /*等价于
        return userMapper.deleteByPrimaryKey(id);
        */
    }

    @Override
    public int createUser(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKey(user);
    }
}
